//
//  GMArtListModel.m
//  gentleman
//
//  Created by 范月成 on 2017/12/5.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMArtListModel.h"
#import "VendorHeader.h"
#import "API.h"
#import "GMArtworkListCell.h"

@interface GMArtListModel ()

@property (nonatomic, copy) NSString *api;
@property (nonatomic, copy) NSDictionary *categories;
@property (nonatomic, assign, readwrite) NSInteger page;
@property (nonatomic, strong, readwrite) NSMutableArray *listDatas;

@end

@implementation GMArtListModel

- (instancetype)init {
    if (self = [super init]) {
        self.page = 0;
        self.listDatas = [NSMutableArray array];
    }
    return self;
}

- (void)getHomePageListDatas:(getListCompleted)completed {
    if (self.page != 0) {
        self.page = 0;
    }
    [self getListWithApi:nil completed:completed];
}

- (void)getHomePageListNext:(getListCompleted)completed {
    self.page ++;
    NSString *api = [NSString stringWithFormat:@"?page=%ld", self.page];
    [self getListWithApi:api completed:completed];
}

- (void)getListWithApi:(NSString *)api
             completed:(getListCompleted)completed {
    [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        request.api = api;
        request.httpMethod = kXMHTTPMethodGET;
        request.responseSerializerType = kXMResponseSerializerRAW;
    } onSuccess:^(id  _Nullable responseObject) {
        [self parserResponse:responseObject completed:completed];
    } onFailure:^(NSError * _Nullable error) {
        !completed?:completed(error, nil);
    }];
}

- (void)parserResponse:(NSData *)response
             completed:(getListCompleted)completed {
    TFHpple *parser = [[TFHpple alloc] initWithHTMLData:response];
    NSArray *artworks = [parser searchWithXPathQuery:kHomePageQuery];
    
    if (artworks.count) {
        NSMutableArray *urls = [NSMutableArray array];
        for (TFHppleElement *artwork in artworks) {
            NSString *photoURLString = artwork.attributes[@"href"];
            [urls addObject:photoURLString];
        }
        [self getArtworkWithUrls:urls completed:completed];
    } else {
        !completed?:completed([NSError errorWithDomain:@"木有数据" code:444 userInfo:nil], nil);
    }
}

- (void)getArtworkWithUrls:(NSArray <NSString *> *)urls
                 completed:(getListCompleted)completed {
    NSMutableArray *idArray = [NSMutableArray array];
    for (NSString *eachURLString in urls) {
        NSArray *splitStrings = [eachURLString componentsSeparatedByString:@"/"];
        NSUInteger splitCount = [splitStrings count];
        [idArray addObject:@[splitStrings[splitCount - 3], splitStrings[splitCount - 2]]];
    }
    
    NSDictionary *parameters = @{@"method":@"gdata", @"gidlist":idArray};
    NSData *httpBody = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    
    AFHTTPSessionManager *sessionManager = [[XMCenter defaultCenter].engine valueForKey:@"sessionManager"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", kGentlManHostOne, kGentlManApi]]];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:httpBody];
    
    NSURLSessionDataTask *dataTask = [sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            dispatch_async_on_main_queue(^{
                !completed?:completed(error, nil);
            });
        } else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            self.page != 0 ?:[self.listDatas removeAllObjects];
            
            NSArray *list = dict[@"gmetadata"];
            
            for (NSInteger i =0; i<list.count; i++) {
                GMArtwork *artwork = [GMArtwork yy_modelWithJSON:list[i]];
                artwork.url = urls[i];
                [self.listDatas addObject:artwork];
            }
            
            dispatch_async_on_main_queue(^{
                !completed?:completed(nil, self.listDatas);
            });
        }
    }];
    [dataTask resume];
}

- (void)getSearchListDatasWithKey:(NSString *)key
                        completed:(getListCompleted)completed {
    NSString *api = [NSString stringWithFormat:@"?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_apply=Apply+Filter&f_search=%@", [key stringByURLEncode]];
    //&advsearch=1&f_sname=on&f_stags=on&f_sr=on&f_srdd=%ld
    self.api = api;
    [self getListWithApi:api completed:completed];
}

- (void)getSearchListNext:(getListCompleted)completed {
    self.page ++;
    NSString *api = [self.api stringByAppendingString:[NSString stringWithFormat:@"&page=%ld", self.page]];
    [self getListWithApi:api completed:completed];
}

- (void)getTagListDatas:(NSString *)tag
              completed:(getListCompleted)completed {
    NSString *api = [[NSString stringWithFormat:@"tag/%@", tag] stringByURLEncode];
    self.api = api;
    [self getListWithApi:api completed:completed];
}

- (void)getTagListNext:(getListCompleted)completed {
    self.page ++;
    NSString *api = [self.api stringByAppendingString:[NSString stringWithFormat:@"/%ld", self.page]];
    [self getListWithApi:api completed:completed];
}

- (void)getCategoryListDatas:(NSString *)category
                   completed:(getListCompleted)completed {
    NSString *api = self.categories[category];
    self.api = api;
    [self getListWithApi:api completed:completed];
}

- (void)getCategoryListNext:(getListCompleted)completed {
    self.page ++;
    NSString *api = [self.api stringByAppendingString:[NSString stringWithFormat:@"/%ld", self.page]];
    [self getListWithApi:api completed:completed];
}

//upload
- (void)getUploaderListDatas:(NSString *)uploader
                   completed:(getListCompleted)completed {
    NSString *api = [[NSString stringWithFormat:@"uploader/%@", uploader] stringByURLEncode];
    self.api = api;
    [self getListWithApi:api completed:completed];
}

- (void)getUploaderListNext:(getListCompleted)completed {
    self.page ++;
    NSString *api = [self.api stringByAppendingString:[NSString stringWithFormat:@"/%ld", self.page]];
    [self getListWithApi:api completed:completed];
}

- (void)getLocalList:(BOOL)isLike
           completed:(getListCompleted)completed{
    NSString *countSql = isLike? @"WHERE isLike = ?":@"WHERE isDownload = ?";
    NSString *querySql = isLike? @"WHERE isLike = ? LIMIT ?,?":@"WHERE isDownload = ? LIMIT ?,?";
    NSInteger count = [[GMArtwork aggregate:@"count(*)" where:countSql arguments:@[@1]] integerValue];
  
    if (self.page && ((count - 20*self.page)<0)) {
        self.page --;
        !completed?:completed([NSError errorWithDomain:@"木有数据" code:444 userInfo:nil], nil);
        return;
    }
    NSInteger queryIndex = count - 20*(self.page+1);
    NSArray *localArts = [GMArtwork objectsWhere:querySql arguments:@[@1, queryIndex<0?@0:@(queryIndex), queryIndex<0?@(queryIndex+20):@20]];
    if (localArts.count) {
        !(self.page == 0)?:[self.listDatas removeAllObjects];
        [self.listDatas addObjectsFromArray:localArts];
        !completed?:completed(nil, self.listDatas);
    } else {
        self.page --;
        !completed?:completed([NSError errorWithDomain:@"木有数据" code:444 userInfo:nil], nil);
    }
}


- (void)getLocalLikeListDatas:(getListCompleted)completed {
    [self getLocalList:YES completed:completed];
}

- (void)getLocalLikeListNext:(getListCompleted)completed {
    self.page++;
    [self getLocalLikeListDatas:completed];
}

- (void)getLocalDownloadListDatas:(getListCompleted)completed {
    [self getLocalList:NO completed:completed];
}

- (void)getLocalDownloadListNext:(getListCompleted)completed {
    self.page++;
    [self getLocalDownloadListDatas:completed];
}

#pragma mark - TableView

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell skeletonStopAnimation];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMArtworkListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMArtworkListCell" forIndexPath:indexPath];
    cell.artwork = self.listDatas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GMArtwork *artwork = self.listDatas[indexPath.row];
    if (self.isDownloadList) {
        [MGJRouter openURL:kRouterDownloadList withUserInfo:@{@"artwork":artwork} completion:nil];
    } else {
        [MGJRouter openURL:kRouterArtworkDetail withUserInfo:@{@"artwork":artwork} completion:nil];
    }
}

- (NSDictionary *)categories {
    if (!_categories) {
        _categories = @{@"Doujinshi":@"doujinshi",
                        @"Manga":@"manga",
                        @"Artist CG Sets":@"artistcg",
                        @"Game CG Sets":@"gamecg",
                        @"Western":@"western",
                        @"Non-H":@"non-h",
                        @"Image Sets":@"imageset",
                        @"Cosplay":@"cosplay",
                        @"Asian Porn":@"asianporn",
                        @"Misc":@"misc"};
    }
    return _categories;
}

@end
